<template>
  <view class="su-label-checkbox">
    <view class="su-label-checkbox__header">
      <text class="su-label-checkbox__title">{{title || ''}}</text>
      <text class="su-label-checkbox__info">（{{info || ''}}）</text>
    </view>
    <view class="su-label-checkbox__options">
      <view class="su-label-checkbox__item" :class="{active:value.includes(item[defaultProps.value])}"
        v-for="(item,index) in options" :key="index" @click="itemClick(item)">
        {{item[defaultProps.label]}}
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    name: "su-label-checkbox",
    model: {
      prop: 'value',
      event: 'change'
    },
    props: {
      value: {
        type: Array,
        default () {
          return []
        }
      },
      defaultProps: {
        type: Object,
        default () {
          return {
            value: 'value',
            label: 'label'
          }
        }
      },
      title: {
        type: String,
        default: ''
      },
      info: {
        type: String,
        default: ''
      },
      options: {
        type: Array,
        default () {
          return []
        }
      },
      maxLength: {
        type: Number,
        default: 0
      },
      readonly:{
        type:Boolean,
        default:false
      },
      disabled:{
        type:Boolean,
        default:false
      }
    },
    data() {
      return {

      };
    },
    methods: {
      itemClick(item) {
        if(this.readonly || this.disabled) return
        const checkedIndex = this.value.findIndex(xitem=>xitem === item[this.defaultProps.value])
        if (this.maxLength && this.value.length >= this.maxLength && checkedIndex===-1) {
          uni.showToast({
            title: `选择不能超过 ${this.maxLength} 项`,
            icon:'none'
          })
          return
        }
        let val = []
        if(checkedIndex===-1){
          val = [...this.value, item[this.defaultProps.value]]
        }else{
          let temp = [...this.value]
          temp.splice(checkedIndex,1)
          val = temp
        }
        this.$emit('change', val)
      }
    }
  }
</script>

<style lang="scss">
  .su-label-checkbox {

    &__header {
      font-size: 32upx;
    }

    &__title {
      font-weight: bold;
      color: #303133;
    }

    &__info {
      font-size: 28upx;
      color: #999;
    }

    &__options {
      display: flex;
      flex-wrap: wrap;
      font-size: 28upx;
      padding: 30upx 0 50upx;
      margin-right: -16upx;
      margin-bottom: -16upx;
    }

    &__item {
      margin-right: 18upx;
      margin-bottom: 18upx;
      padding: 10upx 24upx;
      background-color: #F4F4F5;
      border-radius: 60upx;
      color: #666;
      transition: all 0.3s;

      &:active {
        opacity: 0.6;
      }

      &.active {
        background-color: $u-primary;
        color: #fff;
      }
    }
  }
</style>
